﻿using UnityEngine;
using System.Collections;

public class TroubleCard : Actors 
{
	public Transform m_CardLabel;

	private Animator m_Animator;
	private TextMesh m_LabelTextMesh;
	private bool m_isHovering = false;
	private bool m_CardFlipFinished = false;
	private int m_CardValue;
	private Vector3 m_TargetPos;
	private Vector3 m_InitialPos;
	
	public Animator Animator {get { return m_Animator; }}
	public bool CardFlipFinished {get { return m_CardFlipFinished; } set { m_CardFlipFinished = value; }}
	public int CardValue {get { return m_CardValue; } set { m_CardValue = value; }}
	public Vector3 TargetPos {get { return m_TargetPos; } set { m_TargetPos = value; }}
	public Vector3 InitialPos {get { return m_InitialPos; } set { m_InitialPos = value; }}

	private void Awake()
	{
		m_Animator = GetComponent<Animator>();
		m_LabelTextMesh = m_CardLabel.GetComponent<TextMesh>();
	}

	void Start () 
	{
		m_LabelTextMesh.text = m_CardValue.ToString();
	}

	void Update () 
	{
		if(!m_isHovering)
		{
			aRenderer.material.color = Color.white;
		}
		else
		{
			if((GamesManager.Instance.CurrentGame as TroubleGame).CanClick)
			{
				aRenderer.material.color = Color.green;

				if(Input.GetMouseButtonDown(0))
				{
					OnCardClicked();
				}
			}
		}
	}

	public void OnCardClicked()
	{
		m_Animator.SetTrigger("Click");
		m_isHovering = false;
		(GamesManager.Instance.CurrentGame as TroubleGame).OnCardClicked(this);
		m_TargetPos = aTransform.position = new Vector3(aTransform.position.x, aTransform.position.y, -3f);
	}

	public void UpdateTextMesh()
	{
		m_LabelTextMesh.text = (GamesManager.Instance.CurrentGame as TroubleGame).MovesLeft.ToString();
	}
	
	private void OnMouseEnter()
	{
		if(!(GamesManager.Instance.CurrentGame as TroubleGame).CurrentCard && !(GamesManager.Instance.CurrentGame as TroubleGame).CurrentPlayer.IsComputer)
		{
			m_isHovering = true;
		}
	}
	
	private void OnMouseExit()
	{
		m_isHovering = false;
	}

	private void OnCardFlipDone()
	{
		m_CardFlipFinished = true;
		//m_Animator.SetTrigger("TurnEnd");
	}

	private void OnCardFlipReverseDone()
	{
		(GamesManager.Instance.CurrentGame as TroubleGame).OnCardFlipReverseDone();
	}
}
